﻿using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;

namespace InterPC.SPF.WinFormSample {
    public partial class Form1 : Form {

        private IPAddress SenderIP;
        
        public Form1() {
            InitializeComponent();
        }

        private void btCheckHost_Click(object sender, EventArgs e) {

            // Validate form
            if (!ValidateForm())
                return;

            // Disable button, start marquee
            btCheckHost.Enabled = false;
            bar1.Style = ProgressBarStyle.Marquee;

            // Clear log
            txtLog.Clear();

            // Launch asynchronous Check
            SPFChecker SPF = new SPFChecker(SenderIP, fSender.Text);
            SPF.EnableLogging = true;
            BackgroundWorker BWorker = new BackgroundWorker();
            BWorker.DoWork += new DoWorkEventHandler(BWorker_DoWork);
            BWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BWorker_RunWorkerCompleted);
            BWorker.WorkerReportsProgress = false;
            BWorker.WorkerSupportsCancellation = false;
            BWorker.RunWorkerAsync(SPF);
        }

        private bool ValidateForm() {
            // Reset errors
            errorProvider1.Clear();

            // IP Format
            if (!IPAddress.TryParse(fIP.Text, out SenderIP)) {
                errorProvider1.SetError(fIP, "IP address format is incorrect");
                return false;
            }

            // Sender is not empty
            if (string.IsNullOrEmpty(fSender.Text)) {
                errorProvider1.SetError(fSender, "Sender cannot be empty");
                return false;
            }

            return true;
        }

        void BWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
            // Show results
            CheckResult Result = (CheckResult)e.Result;
            lblResult.Text = Result.SPFResult.ToString();
            txtLog.Text = Result.Log;            

            // Unable button & stop progesssbar animation
            btCheckHost.Enabled = true;
            bar1.Style = ProgressBarStyle.Blocks;
        }

        void BWorker_DoWork(object sender, DoWorkEventArgs e) {
            SPFResult SPFResult = ((SPFChecker)e.Argument).Check_Host();
            e.Result = new CheckResult() {
                SPFResult = SPFResult,
                Log = ((SPFChecker)e.Argument).CheckLog
            };          
        }
    }

    struct CheckResult {
        public SPFResult SPFResult;
        public string Log;
    }
}
